package com.bilibili.servlet;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bilibili.dto.VideoInfo;
import com.bilibili.entity.CommonResult;
import com.bilibili.entity.Page;
import com.bilibili.service.VideoInfoService;
import com.bilibili.service.impl.VideoInfoServiceImpl;

@SuppressWarnings("serial")
@WebServlet("/queryAllNotVideoR")
public class QueryAllNotVideoR extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json; charset=utf-8");
		String state = request.getParameter("state");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		int status = -1,pageNum = 1,pageSize = 5;
		if(state != null) {
			if(state.equals("全部状态")) {
				status = -1;
			}else if(state.equals("待审核")) {
				status = 0;
			}if(state.equals("已通过")) {
				status = 1;
			}if(state.equals("已拒绝")) {
				status = 2;
			}
		}
		if(request.getParameter("pageNum") != null){
			pageNum = Integer.parseInt(request.getParameter("pageNum"));
		}
		
		if(request.getParameter("pageSize") != null){
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		VideoInfo v = new VideoInfo();
		v.setStatus(status);
		if(!"".equals(endTime) && !"".equals(startTime)) {
			v.setStartTime(startTime);
			v.setEndTime(endTime);
		}
		VideoInfoService vis = new VideoInfoServiceImpl();
		Page<VideoInfo> videoInfoPage = vis.selectAllNotVideoR(v,pageNum,pageSize);
		List<VideoInfo> viList = videoInfoPage.getData();
		for (VideoInfo videoInfo : viList) {
			String realPath = "C:/material/video/"+videoInfo.getVideoUrl().split("/")[videoInfo.getVideoUrl().split("/").length-1];
			File file = new File(realPath);
	        if (!file.exists() || !file.isFile()) {
	            throw new IllegalArgumentException("文件不存在或路径不是文件");
	        }
	        long bytes = file.length();
	        double mb = bytes / (1024.0 * 1024.0);
	        DecimalFormat df = new DecimalFormat("#.##");
	        videoInfo.setVideoSize(df.format(mb)+"MB");
		}
		videoInfoPage.setData(viList);
		CommonResult cr = new CommonResult();
		if(videoInfoPage.getData().size() != 0) {
			cr.setCode(200);
			cr.setData(videoInfoPage);
		}else {
			cr.setCode(409);
		}
		response.getWriter().write(cr.toJSONString());
	}
}
